import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_widgets/widgets/searchBar/kq_search_bar.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';

/// 通用列表对话框
///
/// @author 周卓
///
class KqListDialog<T> extends AlertDialog {
  /// 数据源
  final List<T> items;

  /// 转换 T -> String 转换
  final String Function(int index, T item)? nameConvert;

  /// 回调
  final Function(int index, T item)? callback;

  /// 是否显示搜索，[searchEnable]=true时，需要配合[onSearchItem]使用，默认false
  final bool searchEnable;

  /// 搜索内容匹配方法，仅[searchEnable]=true时生效
  final bool Function(String searchText, T item)? onSearchItem;

  /// 自定义item布局
  final Widget? Function(int index, T item)? customItemBuilder;

  const KqListDialog(
      {Key? key,
      required this.items,
      this.searchEnable = false,
      this.onSearchItem,
      this.nameConvert,
      this.customItemBuilder,
      this.callback})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var padding = MediaQuery.of(context).viewInsets.bottom;
    return UnconstrainedBox(
        child: Padding(
      padding: EdgeInsets.only(bottom: padding),
      child: SizedBox(
          width: 320.r,
          child: Material(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(8.r))),
              color: KqThemeManager.instance.getConfig().dialogConfig.bgColor ??
                  KqThemeColors.bgWhite,
              child: KqSearchListView(
                items: items,
                searchEnable: searchEnable,
                onSearchItem: onSearchItem,
                nameConvert: nameConvert,
                customItemBuilder: customItemBuilder,
                callback: callback,
              ))),
    ));
  }
}

/// 搜索列表
class KqSearchListView<T> extends StatefulWidget {
  /// 数据源
  final List<T> items;

  /// 是否显示搜索，默认不显示
  final bool searchEnable;

  /// 转换 T -> String 转换
  final String Function(int index, T item)? nameConvert;

  /// 搜索内容匹配方法，仅[searchEnable]=true时生效
  final bool Function(String searchText, T item)? onSearchItem;

  /// 自定义Item布局
  final Widget? Function(int index, T item)? customItemBuilder;

  /// 回调
  final Function(int index, T item)? callback;

  /// 圆角大小，默认8
  final double? radius;

  /// 字体大小，默认16
  final double? fontSize;

  const KqSearchListView(
      {Key? key,
      required this.items,
      this.onSearchItem,
      this.searchEnable = false,
      this.nameConvert,
      this.radius,
      this.customItemBuilder,
      this.fontSize,
      this.callback})
      : super(key: key);

  @override
  KqSearchListViewState createState() => KqSearchListViewState<T>();
}

class KqSearchListViewState<T> extends State<KqSearchListView<T>> {
  /// 搜索内容
  var _searchText = "";

  List<T> _allItems = [];

  List<T> _showItems = [];

  @override
  void initState() {
    _allItems = widget.items;
    _showItems = [..._allItems];
    super.initState();
  }

  @override
  void didUpdateWidget(covariant KqSearchListView<T> oldWidget) {
    if (oldWidget.items != widget.items) {
      _allItems = widget.items;
      searchData();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // 小诸葛规范，最多显示6个，多余滚动
    var maxHeight = 6 * 50.r;
    var realHeight = _showItems.length * 50.r;

    final List<Widget> children = <Widget>[];

    return ClipRRect(
      borderRadius: BorderRadius.all(Radius.circular(widget.radius ?? 8.r)),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (widget.searchEnable)
            KqSearchBar(
              newValue: _searchText,
              onChanged: (value) {
                _searchText = value;
                searchData();
              },
              onCancel: () {
                _searchText = "";
                searchData();
              },
              onCleared: () {
                _searchText = "";
                searchData();
              },
            ),
          LimitedBox(
            maxHeight: min(realHeight, maxHeight),
            child: ListView.builder(
              itemCount: _showItems.length,
              itemBuilder: (context, index) {
                var item = _showItems[index];
                String title;
                if (widget.nameConvert != null) {
                  title = widget.nameConvert!(index, item);
                } else {
                  if (item is String) {
                    title = item;
                  } else if (item is Map) {
                    title = item['title'];
                  } else {
                    title = '';
                  }
                }
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    KqInkWell(
                      onTap: () => {
                        if (widget.callback != null)
                          {widget.callback!(index, item)}
                      },
                      child: Container(
                        height: 50.r,
                        alignment: Alignment.center,
                        width: double.infinity,
                        padding:
                            EdgeInsets.symmetric(vertical: 0, horizontal: 20.r),
                        child: widget.customItemBuilder?.call(index, item) ??
                            Text(
                              title,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: widget.fontSize ?? 16.sp,
                                  color: KqThemeManager.instance
                                          .getConfig()
                                          .dialogConfig
                                          .itemTextColor ??
                                      KqThemeColors.text26),
                            ),
                      ),
                    ),
                    if (index < (_showItems.length - 1)) const KqDivider()
                  ],
                );
              },
            ),
            // child: SingleChildScrollView(
            //   child: dialogChild,
            // ),
          ),
        ],
      ),
    );
  }

  void searchData() {
    setState(() {
      if (_searchText.isEmpty) {
        _showItems = [..._allItems];
      } else {
        _showItems.clear();
        for (T item in _allItems) {
          bool showItem = widget.onSearchItem?.call(_searchText, item) ?? true;
          if (showItem) {
            _showItems.add(item);
          }
        }
      }
    });
  }
}
